<?php

namespace App\Service\CommodityService;
use App\Service\AppService\SystemCacheConfigService;
use App\Service\BaseService;
use App\Service\Code\Normal;
use App\Service\OrderService\OrderRouteService\Shopubuy;
use App\Model\CommodityModel\SupplierCompany;
use Hyperf\DbConnection\Db;

/**
 * 行云供应商商品资料拉取
 * @author chenshubo
 */
class SupplierCommodityUnibuyPullLogService extends BaseService
{
    const PULL_FLAG = 'shopubuy';
    const TIME_WAIT = 60;//分钟
    const PULL_USER_COUNT = 10;//每次同时拉取供应商的数量
    
    /**
     * 开启计划任务
     */
    public function runTask($start_date='')
    {

        //系统业务配置里面管控配置参数
        $config = SystemCacheConfigService::instance()->getCacheInfoBySystemCode('channel_task_user_limit');
        if( empty($config) ) {
            return Normal::returnCode(Normal::FAIL,'参数未配置');
        }
        //所有供应商拉取完成间隔时间
        $SupplierPullWaitTime = $config['SupplierPullWaitTime'];
        $SupplierPullWaitTime = $SupplierPullWaitTime > 0 ? $SupplierPullWaitTime : self::TIME_WAIT;
        //预计下次拉取商品时间
        $CommodityGetNetPeriod = date("Y-m-d H:i:s",time() + $SupplierPullWaitTime * 60 );
        
        $res = SupplierCommodityPullLogService::instance()->getWaitPullSupplierWareHouseInfoBySupplierCode(self::PULL_FLAG);
        if( $res['code'] != Normal::SUC ) {
            return $res;
        }
        
        $supplier = $res['data'];
        
        //获取供应商参数
        $company_code   = $supplier['ThirdPartyPlatformCode'] ? $supplier['ThirdPartyPlatformCode'] : $supplier['SupplierCode'];
        $SupplierID     = $supplier['SupplierID'];
        
        //初始化拉取状态
        $updateArr = [
            'CommodityGetTaskStatus'    => 0,
            'CommodityGetFinishCount'   => 0,
            'CommodityGetFinishUseTime' => 0.000,
        ];
        SupplierCompany::instance()->where('ID',$SupplierID)->update($updateArr);
        
        $CommodityGetStartTime = microtime(true);
        $apiBody = $supplier['JsonBody'];
        if( !empty($start_date) ) {
            $apiBody['start_time'] = $start_date;
        }
        
        $start_date = !empty($apiBody['start_time']) ? $apiBody['start_time'] : date('Y-m-d');
        $end_date   = date('Y-m-d');
        
        //获取全部日期
        $dates      = $this->showMonthRange($start_date,$end_date);
        
        //处理根据日期拉取情况
        $page = 1;
        $currentLastPage = $currentPage = $CommodityGetTotal = 0;
        
        foreach ($dates as $page_key=>$date)
        {

            if($page_key == 0 ){
                //第一页需要推送数据
                $MessageBody  = [
                    'SupplierID'        => $SupplierID,
                    'SupplierCode'      => $company_code,
                    'IsFirstPage'       => 1,
                    'DataPage'          => 1,
                    'IsLastPage'        => 0,
                    'GoodsItemList'     => []
                ];
                SupplierCommodityPullLogService::instance()->publish($MessageBody);
            }
            $innerPage = 1;

            while ( true )
            {
                //根据分类获取商品
                $queryBody = [
                    'page'          => $innerPage,
                    'limit'         => isset($apiBody['limit']) ? $apiBody['limit'] : 100,
                    'startTime'     =>  date('Y-m-d 00:00:00',strtotime($date)),
                    'endTime'        => date('Y-m-d 23:59:59',strtotime($date)),
                ];
                
                try {
                    $resQuery = Shopubuy::instance()->queryGoodsList(['apiBody'   => $apiBody,'queryBody' => $queryBody ]);
                    if( $resQuery['code'] != Normal::SUC ) {
                        SupplierCompany::instance()->where('ID',$SupplierID)->update(['CommodityGetContents'=>$resQuery['msg'],'CommodityGetTaskStatus'=>3]);
                        break;
                    }
                    SupplierCompany::instance()->where('ID',$SupplierID)->update(['CommodityGetContents'=>$resQuery['msg']]);
                } catch ( \Throwable $t ) {
                    SupplierCompany::instance()->where('ID',$SupplierID)->update(['CommodityGetContents'=>$t->getMessage(),'CommodityGetTaskStatus'=>3]);
                    break;
                }

                //如果获取数据发送至消息队列，发送批量
                if( empty($resQuery['data']['list']) ) {

                    $currentLastPage = $currentPage;
                    break;
                }
                
                $pull_count = count($resQuery['data']['list']);
                $CommodityGetTotal += $pull_count;
                $updateArr = [
                    'CommodityGetTaskStatus'    => 1,
                    'CommodityGetFinishCount'   => Db::raw("CommodityGetFinishCount+{$pull_count}")
                ];
                SupplierCompany::instance()->where('ID',$SupplierID)->update($updateArr);
                $currentPage = ($page * $page_key) + $innerPage + $currentLastPage;
                $MessageBody  = [
                    'SupplierID'        => $SupplierID,
                    'SupplierCode'      => $company_code,
                    'IsFirstPage'       => 0,
                    'DataPage'          => $currentPage,
                    'IsLastPage'        => 0,
                    'GoodsItemList'     => $resQuery['data']['list']
                ];
                SupplierCommodityPullLogService::instance()->publish($MessageBody);
                $innerPage++;
            }
        }
        
        //更新总数量
        $MessageBody  = [
            'SupplierID'        => $SupplierID,
            'SupplierCode'      => $company_code,
            'IsFirstPage'       => 0,
            'DataPage'          => 1,
            'IsLastPage'        => 1,
            'GoodsItemList'     => []
        ];
        SupplierCommodityPullLogService::instance()->publish($MessageBody);
        
        //拉取完成
        $updateArr = [
            'CommodityGetTaskStatus'    => 2,
            'CommodityGetContents'      => '拉取完成',
            'CommodityGetFinishUseTime' => bcsub(microtime(true),$CommodityGetStartTime,3),
            'CommodityGetNetPeriod'     => $CommodityGetNetPeriod
        ];
        SupplierCompany::instance()->where('ID',$SupplierID)->update($updateArr);
        return Normal::returnCode(Normal::SUC,'拉取完成');
    }

    //php 获取开始日期与结束日期之间所有月份
    public function showMonthRange($start, $end)
    {
        $end = date('Y-m-d', strtotime($end)); // 转换为天
        $range = [];
        $i = 0;
        do {
            $month = date('Y-m-d', strtotime($start . ' + ' . $i . ' day'));
            //echo $i . ':' . $month . '<br>';
            $range[] = $month;
            $i++;
        } while ($month < $end);

        return $range;
    }
}